<script setup lang="ts" name="Map">
import layersTree from "./layersTree.js";
import "@arcgis/core/assets/esri/themes/light/main.css";
import esriConfig from "@arcgis/core/config.js";
import * as urlUtils from "@arcgis/core/core/urlUtils.js";
import * as reactiveUtils from "@arcgis/core/core/reactiveUtils.js";

import Map from "@arcgis/core/Map.js";
import Basemap from "@arcgis/core/Basemap.js";
import Graphic from "@arcgis/core/Graphic.js";
// import * as geometry from "@arcgis/core/geometry.js";
// import esriRequest from "@arcgis/core/request.js";

import Extent from "@arcgis/core/geometry/Extent.js";
import SpatialReference from "@arcgis/core/geometry/SpatialReference.js";
// import * as promiseUtils from "@arcgis/core/core/promiseUtils.js";
// import Collection from "@arcgis/core/core/Collection.js";
import Polygon from "@arcgis/core/geometry/Polygon.js";
// import * as geometryEngine from '@arcgis/core/geometry/geometryEngine.js'
// import * as geometryEngineAsync from '@arcgis/core/geometry/geometryEngineAsync.js'
// import * as projection from '@arcgis/core/geometry/projection.js'

import MapView from "@arcgis/core/views/MapView.js";
import GroupLayer from "@arcgis/core/layers/GroupLayer.js";
import FeatureLayer from "@arcgis/core/layers/FeatureLayer.js";
import MapImageLayer from "@arcgis/core/layers/MapImageLayer.js";
import GraphicsLayer from "@arcgis/core/layers/GraphicsLayer.js";
import TileLayer from "@arcgis/core/layers/TileLayer.js";
// import VectorTileLayer from '@arcgis/core/layers/VectorTileLayer.js'
// import GeoJSONLayer from '@arcgis/core/layers/GeoJSONLayer.js'
// import WebTileLayer from '@arcgis/core/layers/WebTileLayer.js'
// import ImageryLayer from '@arcgis/core/layers/ImageryLayer.js'
import SimpleFillSymbol from "@arcgis/core/symbols/SimpleFillSymbol";

import Home from "@arcgis/core/widgets/Home.js";
import Legend from "@arcgis/core/widgets/Legend.js";
import Bookmarks from "@arcgis/core/widgets/Bookmarks.js";
import Expand from "@arcgis/core/widgets/Expand.js";
import Sketch from "@arcgis/core/widgets/Sketch.js";
import ScaleBar from "@arcgis/core/widgets/ScaleBar.js";
import Print from "@arcgis/core/widgets/Print.js";
import CoordinateConversion from "@arcgis/core/widgets/CoordinateConversion.js";
import LayerList from "@arcgis/core/widgets/LayerList.js";
import Measurement from "@arcgis/core/widgets/Measurement.js";
// import SketchViewModel from '@arcgis/core/widgets/Sketch/SketchViewModel.js'
// import Swipe from '@arcgis/core/widgets/Swipe.js'
// import Fullscreen from '@arcgis/core/widgets/Fullscreen.js'
// import BasemapToggle from '@arcgis/core/widgets/BasemapToggle.js'
// import DistanceMeasurement2D from '@arcgis/core/widgets/DistanceMeasurement2D.js'
// import AreaMeasurement2D from '@arcgis/core/widgets/AreaMeasurement2D.js'
// import Slider from '@arcgis/core/widgets/Slider.js'
// import ProjectParameters from '@arcgis/core/rest/support/ProjectParameters.js'

// import Query from '@arcgis/core/rest/support/Query.js'
// import FeatureSet from '@arcgis/core/rest/support/FeatureSet.js'
// import LinearUnit from '@arcgis/core/rest/support/LinearUnit.js'
// import IdentifyParameters from '@arcgis/core/rest/support/IdentifyParameters.js'
// import FindParameters from '@arcgis/core/rest/support/FindParameters.js'
// import AreasAndLengthsParameters from '@arcgis/core/rest/support/AreasAndLengthsParameters.js'

import axios from "axios";
import { LandApi, LandVO } from "@/api/zszx/land";
import LandForm from "@/views/zszx/land/LandForm.vue";
/** 添加/修改操作 */
const landFormRef = ref();
const openLandForm = (type: string, id?: number) => {
  landFormRef.value.open(type, id);
};

defineOptions({ name: "Map" });

const message = useMessage();
const instance = getCurrentInstance();
if (!instance) {
  throw new Error("getCurrentInstance 只能在 setup() 或生命周期钩子中使用。");
}
const { proxy } = instance;

const allLayersTree = ref(layersTree);
const viewWidth = ref(`calc(100%)`); //ref(`calc(100% - 50px)`)
//:style="{ height: 'calc(100vh - var(--top-tool-height) - var(--tags-view-height) )' }"
urlUtils.addProxyRule({
  urlPrefix: "http://16.37.64.24:6080", //配置文件proxy.config中的地址,要请求的地址
  proxyUrl: "http://16.37.64.129/arcgis_js_api/resource-proxy/proxy.ashx", //部署的代理文件地址
});

esriConfig.assetsPath = "./assets";
// esriConfig.fontsUrl = '/assets/esri/themes/base/fonts'
esriConfig.apiKey =
  "AAPK4fca9f2ecd52420eaa3999caf4564aebmOMdabD74JMoeUFUL0QUbhzbIUTdxJI0cyx5aU4rEu3XUXB-OohSYFgPEtbv7eNU";
esriConfig.geometryServiceUrl =
  "http://16.37.64.24:6080/arcgis/rest/services/Utilities/Geometry/GeometryServer";
// esriConfig.proxyUrl=''

var measurement = new Measurement();
const measureflag = ref(0);

const sketchLayer = new GraphicsLayer({ title: "自绘草图层" });

const featureCollection = ref<any[]>([]); //拼接属性字段

const loading = ref(true); // 列表的加载中
const landList = ref<LandVO[]>([]); // 列表的数据
const total = ref(0); // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: -1,
  id: undefined,
  landNo: undefined,
  landCertificate: undefined,
  landLocation: undefined,
  landDistrict: undefined,
  landTownship: undefined,
  // landVillage: undefined,
  landArea: undefined,
  levyStandards: undefined,
  landQlxz: undefined,
  landApprovedUse: undefined,
  landActualUse: undefined,
  landLevel: undefined,
  landBdcdyh: undefined,
  status: undefined,
  creator: undefined,
  createTime: [],
});
const columns = [
  {
    alias: "宗地ID",
    name: "id",
    type: "long" as const,
  },
  {
    alias: "地块编号",
    name: "landNo",
    type: "string" as const,
  },
  {
    alias: "土地证号",
    name: "landCertificate",
    type: "string" as const,
  },
  {
    alias: "所属区县",
    name: "landDistrict",
    type: "string" as const,
  },
  {
    alias: "所属乡镇",
    name: "landTownship",
    type: "string" as const,
  },
  {
    alias: "所属村",
    name: "landVillage",
    type: "string" as const,
  },
  {
    alias: "面积",
    name: "landArea",
    type: "double" as const,
  },
  {
    alias: "批准用途",
    name: "landApprovedUse",
    type: "string" as const,
  },
  {
    alias: "实际用途",
    name: "landActualUse",
    type: "string" as const,
  },
  {
    alias: "土地级别",
    name: "landLevel",
    type: "string" as const,
  },
  {
    alias: "不动产单元号",
    name: "landBdcdyh",
    type: "string" as const,
  },
  {
    alias: "备注",
    name: "remark",
    type: "string" as const,
  },
];

//宗地档案图层
var landsGroupLayer = new GroupLayer({
  title: "宗地信息",
  id: "rentLands",
});

const basemap = new Basemap({
  title: "底图",
  baseLayers: [
    new TileLayer({
      url: "http://16.37.64.24:6080/arcgis/rest/services/ygyx/XA102023410800YGYX/MapServer",
      // url: 'http://16.37.64.24:6080/arcgis/rest/services/jcdl/XA102016410800XZQH_X/MapServer',//调试临时用
      title: "焦作市2023年影像",
      id: "basemap01",
      visible: true,
    }),
  ],
});
var view;
const map = new Map({
  basemap: basemap,
  // ground: "world-elevation",
});
console.log(map);
const project_url =
  "http://16.37.64.23:6080/arcgis/rest/services/Utilities/Geometry/GeometryServer/project";

onMounted(() => {
  loadView();
});

const gotoExtent = async (row) => {
  let landCoordinate = JSON.parse(row.landCoordinate);
  console.log("landCoordinate", landCoordinate);
  // let ly = view.map.findLayerById('archive' + row.archiveId)
  if (row.landCoordinate) {
    const fillSymbol = new SimpleFillSymbol({
      color: [0, 255, 255, 0.5],
      outline: {
        color: [255, 255, 0],
        width: 2,
      },
    });

    // const fillSymbol = {
    //   type: 'simple-fill',
    //   color: [0, 255, 255, 0.5],
    //   outline: {
    //     color: [255, 255, 0],
    //     width: 2
    //   }
    // }
    const rings = landCoordinate.features[0].geometry.coordinates;
    const polygon = new Polygon({
      spatialReference: new SpatialReference({ wkid: 4526 }),
      rings: rings,
    });
    const graphic = new Graphic({
      geometry: polygon,
      symbol: fillSymbol,
    });
    console.log("polygon", polygon);
    view.graphics.removeAll();
    view.graphics.addMany([graphic]);
    // view.extent=polygon.extent
    await gotoExtentByProject(polygon, project_url); // 涉及坐标转换问题view.extent=polygon.extent
  } else {
    proxy.$modal.msgError("定位失败，地块无坐标!");
    view.graphics.removeAll();
    // view.goto({ center: [113.10, 35.15], scale: 350000})
    return false;
  }
};
defineExpose({
  gotoExtent,
});

// function clickRow(row, column, event) {
//   // console.log(row, column, event)
//   if (!row.landCoordinate) {
//     proxy.$modal.msgError('该地块未录入坐标！')
//     return
//   }

//   const fillSymbol = new SimpleFillSymbol({
//     color: [0, 255, 255, 0.5],
//     outline: {
//       color: [255, 255, 0],
//       width: 2
//     }
//   })
//   const polygon = new Polygon({
//     rings: JSON.parse(row.landCoordinate).features[0].geometry.coordinates
//   })
//   const graphic = new Graphic({
//     geometry: polygon,
//     symbol: fillSymbol
//   })
//   view.graphics.removeAll()
//   view.graphics.addMany([graphic])
//   gotoExtent(row) // view.extent = polygon.extent
// }

const gotoExtentByProject = async (polygon, project_url) => {
  let geometries = [
    {
      x: polygon.extent.xmin,
      y: polygon.extent.ymin,
    },
    {
      x: polygon.extent.xmax,
      y: polygon.extent.ymax,
    },
  ];
  console.log(geometries, JSON.stringify(geometries));
  await view.when(async () => {
    //
    console.log(
      project_url +
        "?f=pjson&inSR=" +
        polygon.extent.spatialReference.wkid +
        "&outSR=" +
        view.spatialReference.wkid +
        "&transformation=&transformForward=false&geometries=" +
        JSON.stringify({ geometryType: "esriGeometryPoint", geometries: geometries })
    );
    let extRes = await axios.get(
      project_url +
        "?f=pjson&inSR=" +
        polygon.extent.spatialReference.wkid +
        "&outSR=" +
        view.spatialReference.wkid +
        "&transformation=&transformForward=false&geometries=" +
        JSON.stringify({ geometryType: "esriGeometryPoint", geometries: geometries })
    );
    console.log(polygon.extent.spatialReference.wkid, view.spatialReference.wkid, extRes);
    const ext = new Extent({
      xmin: extRes.data.geometries[0].x,
      ymin: extRes.data.geometries[0].y,
      xmax: extRes.data.geometries[1].x,
      ymax: extRes.data.geometries[1].y,
      spatialReference: new SpatialReference({ wkid: view.spatialReference.wkid }),
    });
    view.extent = ext;
  });
};

const switchLayer = () => {
  if (viewWidth.value == `calc(100% - 250px)`) {
    viewWidth.value = `calc(100%)`;
    proxy.$refs["layerButtonRef"].classList.remove("active");
  } else {
    viewWidth.value = `calc(100% - 250px)`;
    proxy.$refs["layerButtonRef"].classList.add("active");
  }
};

const generatePopupTemplate = (columns) => {
  let fieldInfos = [] as any[];
  for (let i = 0; i < columns.length; i++) {
    const fieldInfo = columns[i];
    fieldInfos.push({
      label: fieldInfo.alias,
      fieldName: fieldInfo.name,
    });
  }
  return {
    title: "{landNo}-地块信息",
    outFields: ["*"],
    returnGeometry: true,
    content: [
      {
        type: "fields",
        fieldInfos: fieldInfos,
      },
    ],
    actions: [
      {
        title: "查看宗地详情",
        id: "landDetail",
        type: "button" as const,
        // image:""
      },
    ],
  };
};

/** 查询列表 */
const getList = async () => {
  loading.value = true;
  try {
    const data = await LandApi.getLandPage(queryParams);
    landList.value = data.list;
    total.value = data.total;
    updateFeatureCollection(landList.value);
    let grouplayers = toGroupLayers(featureCollection.value);
    // console.log(landList.value, featureCollection.value, grouplayers)
    landsGroupLayer.addMany(grouplayers);
    map.add(landsGroupLayer);
  } finally {
    loading.value = false;
  }
};

/** 展示geojson */
const updateFeatureCollection = (lands) => {
  // console.log("updateFeatureCollection",lands)
  for (let i = 0; i < lands.length; i++) {
    const land = lands[i];
    if (
      land.landCoordinate !== null &&
      land.landCoordinate.trim() !== "" &&
      land.landCoordinate !== undefined
    ) {
      let geojson = JSON.parse(land.landCoordinate);
      for (let j = 0; j < geojson.features.length; j++) {
        let feature = geojson.features[j];
        //补上properties
        if (
          !feature.hasOwnProperty("properties") ||
          JSON.stringify(feature.properties) == "{}" ||
          JSON.stringify(feature.properties) == "null"
        ) {
          // console.log('修改前', feature.properties, feature.hasOwnProperty('properties'))
          let attr: { [key: string]: any } = {};
          for (let k = 0; k < columns.length; k++) {
            let name = columns[k].name; //字段名
            // let title = this.columns[k].title//字段中文名//arcgis不用，用英文
            let title = columns[k].name;
            attr[title] = land[name];
          }
          land.landNo ? (attr.name = land.landNo) : (attr.name = "无地块名称"); //给图层添加名称
          // console.log('land', land)
          // console.log('i--', i,j--', j,attr--', att)
          feature.properties = attr;
          //console.log('修改后新生成属性', feature.properties)
        }
        // console.log('修改后geojson', geojson)
        featureCollection.value.push(geojson);
      }
    }
  }
};

const toGroupLayers = (featureCollection) => {
  let gLayer: FeatureLayer[] = [];
  for (let i = 0; i < featureCollection.length; i++) {
    let fea = featureCollection[i];
    const blob = new Blob([JSON.stringify(fea)], { type: "application/json" });
    // create new geojson layer using the blob url
    const url = URL.createObjectURL(blob);
    // console.log("fea", JSON.parse(JSON.stringify(fea.features[0].properties)))
    const polygon = {
      type:
        fea.features[0].geometry.type.toLowerCase() == "multipolygon"
          ? "polygon"
          : fea.features[0].geometry.type.toLowerCase(),
      rings: fea.features[0].geometry.coordinates,
      spatialReference: new SpatialReference({ wkid: 4526 }),
    };
    const polygonGraphic = new Graphic({
      geometry: polygon,
      attributes: JSON.parse(JSON.stringify(fea.features[0].properties)),
      symbol: {
        type: "simple-fill",
        color: [255, 255, 255, 0],
        // style: "solid",
        outline: {
          color: "red",
          width: 2,
        },
      },
    });
    const layer = new FeatureLayer({
      popupEnabled: true,
      outFields: ["*"],
      fields: columns,
      popupTemplate: generatePopupTemplate(columns),
      objectIdField: "id",
      title: fea.features[0].properties.name,
      id: "id" + fea.features[0].properties.id,
      copyright: "焦作市基础地理信息中心",
      spatialReference: {
        wkid: 4526,
      },
      geometryType: "polygon",
      source: [polygonGraphic],
    });
    // const ly = new GeoJSONLayer({
    //     "popupEnabled": true,
    //     "outFields": ['*'],
    //     "fields": columns,
    //     "popupTemplate": generatePopupTemplate(columns),
    //     "objectIdField": 'id',
    //     "url": url,
    //     "title": fea.features[0].properties.name,
    //     "id": 'LAND' + fea.features[0].properties.id,
    //     "copyright": "焦作市基础地理信息中心",
    //     // "spatialReference": {
    //     //     "wkid": 4526,
    //     //     "latestWkid": 4526
    //     // },//不生效，geojsonlayer默认4326 WGS84
    //     // "opacity": 0.5,
    // })
    layer.renderer = {
      type: "simple",
      symbol: {
        type: "simple-fill",
        color: [255, 255, 255, 0],
        // style: "solid",
        outline: {
          color: "red",
          width: 2,
        },
      },
    };
    gLayer.push(layer);
  }
  return gLayer;
};

const loadView = () => {
  //二维视图
  const mapView = new MapView({
    container: "view-div",
    map: map,
    center: [113.1, 35.15],
    // zoom: 13,
    scale: 350000,
    popup: {
      dockEnabled: true, //是否可停靠
      dockOptions: {
        buttonEnabled: true, //是否显示停靠按钮
        // breakpoint: false,
        position: "auto",
      },
      highlightEnabled: true,
    },
    popupEnabled: true,
    constraints: {
      snapToZoom: false,
    },
  });
  view = mapView;
  console.log(222, view);
  measurement.view = view;

  const layerList = new LayerList({
    view: view,
  });
  const layerListExpand = new Expand({
    expandTooltip: "展开图层列表",
    expanded: false,
    view: view,
    content: layerList,
  });
  const home = new Home({
    view: view,
  });
  const bookmarks = new Bookmarks({
    view: view,
    dragEnabled: true,
    visibleElements: {
      addBookmarkButton: true,
      editBookmarkButton: true,
      time: false, // don't show the time (h:m:s) next to the date
    },
    // editingEnabled: true
  });
  const bkExpand = new Expand({
    expandTooltip: "展开书签",
    view: view,
    content: bookmarks,
    expanded: false,
  });
  const scaleBar = new ScaleBar({
    view: view,
    unit: "dual", // The scale bar displays both metric and non-metric units.
  });
  const ccWidget = new CoordinateConversion({
    view: view,
  });
  const sketch = new Sketch({
    layer: sketchLayer,
    view: view,
    creationMode: "update", // graphic will be selected as soon as it is created
  });
  const print = new Print({
    view: view,
    printServiceUrl:
      "http://16.37.64.23:6080/arcgis/rest/services/Utilities/PrintingTools/GPServer/Export%20Web%20Map%20Task",
  });
  const printExpand = new Expand({
    expandTooltip: "展开打印",
    view: view,
    content: print,
    expanded: false,
  });
  const legend = new Legend({
    view: view,
    style: "card",
  });

  view.ui.remove("attribution"); //移除底部ESRI logo
  view.ui.add(sketch, "top-right"); //添加草图工具箱
  view.ui.add(home, "top-left");
  view.ui.add(layerListExpand, "top-left"); // Add widget to the view
  view.ui.add(bkExpand, "top-left");
  view.ui.add(new Expand({ view, content: legend }), "top-left"); //图例
  view.ui.add(ccWidget, "bottom-left");
  view.ui.add(scaleBar, { position: "bottom-right" }); //比例尺
  //   view.ui.add("toggleDiv", "top-left"); //开关
  view.ui.add("topbar", "top-left"); //测量的
  // view.ui.add(proxy.onlineToggle, "bottom-right");//在线底图切换
  // view.ui.add(proxy.offlineToggle, "bottom-right");//离线底图切换
  view.ui.add(printExpand, "bottom-right");
  view.ui.add(measurement, "bottom-right");
  getList();
  // reactiveUtils.on(
  //   () => view.popup,
  //   'trigger-action',
  //   (event) => {
  //     if (event.action.id === 'landDetail') {
  //       const attributes = view.popup.selectedFeature.attributes
  //       console.log('触发', attributes)
  //       nextTick(() => {
  //         openLandForm('update', attributes.id)
  //       })
  //     }
  //   }
  // )
  //旧版本
  view.popup.on("trigger-action", async function (event) {
    if (event.action.id === "landDetail") {
      const attributes = view.popup.selectedFeature.attributes;
      console.log("触发", attributes);
      nextTick(() => {
        openLandForm("update", attributes.id);
      });
    }
  });
  view
    .when(function () {
      console.log("inited");
    })
    .catch(function (error) {
      console.log(error);
    });
};

const changeLayers = async (node, isChecked, childreHasChecked) => {
  console.log("点击节点，是否勾选，子是否勾选:", node, isChecked, childreHasChecked);
  console.log(proxy.$refs.layerManagerTreeRef.getCheckedKeys());
  if (isChecked) {
    //此处添加Grouplayer图层多,防止卡死
    if (node.type === "group" || !node.url) {
      proxy.$modal.notify("当前节点图层过多，请选择子节点");
      return;
    } else if (node.type === "tile") {
      let ly = new TileLayer({
        id: node.id,
        title: node.title,
        url: node.url,
      });
      map.add(ly);
      map.reorder(landsGroupLayer, map.layers.length - 1);
    } else if (node.type === "map-image") {
      let ly = new MapImageLayer({
        id: node.id,
        title: node.title,
        url: node.url,
      });
      console.log("检查未生成弹出表图层：", ly);
      map.add(ly);
      map.reorder(landsGroupLayer, map.layers.length - 1);
      let checkedNodes = proxy.$refs.layerManagerTreeRef.getCheckedNodes();
      ly.when(() => {
        setPopupByNode(node);
        for (const sublayer of ly.allSublayers) {
          sublayer.visible = false;
        }
        // for (let i = 0; i < ly.allSublayers.length; i++) {
        //   ly.allSublayers.items[i].visible = false
        // }
      });

      ly.loadAll().then(() => {
        for (let i = 0; i < checkedNodes.length; i++) {
          console.log(checkedNodes[i].title, checkedNodes[i].id);
          let sublayerId = checkedNodes[i].id.split("-")[1];
          if (sublayerId) {
            let sublayer = ly.allSublayers.find(function (layer) {
              // return layer.title == checkedNodes[i].title
              return layer.id == sublayerId;
            });
            if (sublayer) {
              sublayer.visible = true;
            }
          }
        }
      });
    } else if (node.type == "Feature Layer") {
      // console.log(that.$refs.layerManagerTree.getCheckedKeys())
      let layerId = node.id.split("-")[0];
      let sublayerTitle = node.title;
      showSublayer(layerId, sublayerTitle, true);
    } else if (node.type == "Group Layer") {
      console.log(node.layers, node.id); //inherited
      let layerId = node.id.split("-")[0];
      let sublayerTitle = node.title;
      showSublayer(layerId, sublayerTitle, true);
    }
  } else {
    //取消勾选
    if (node.type == "Feature Layer") {
      console.log("取消勾选", node);
      let layerId = node.id.split("-")[0];
      let sublayerId = node.id.split("-")[1];
      let sublayerTitle = node.title;
      showSublayerBySubid(layerId, sublayerId, false);
      // that.showSublayer(layerId, sublayerTitle, false)
    } else if (node.type == "Group Layer") {
      console.log(node.layers, node.id); //inherited
      let layerId = node.id.split("-")[0];
      let sublayerId = node.id.split("-")[1];
      let sublayerTitle = node.title;
      showSublayerBySubid(layerId, sublayerId, false);
      // that.showSublayer(layerId, sublayerTitle, false)
    } else {
      //否则移除
      let maply = map.findLayerById(node.id);
      // that.$refs.layerManagerTree.setChecked(node.id ,false,false)
      if (maply) {
        map.remove(maply);
      }
    }
  }
  // console.log(map.layers)
};
const showSublayerBySubid = (layerId, subid, isShow) => {
  let maply = map.findLayerById(layerId);
  if (!maply) {
    console.warn(`未找到图层：${layerId}`);
    return;
  }
  let sublayer = maply.allSublayers.find(function (layer) {
    return layer.id == subid;
  });
  sublayer.visible = isShow;
};
const showSublayer = (layerId, sublayerTitle, isShow) => {
  let maply = map.findLayerById(layerId);
  console.log("maply", maply);
  maply?.when(() => {
    let sublayer = maply?.allSublayers.find(function (layer) {
      return layer.title == sublayerTitle;
    });
    sublayer.visible = isShow;
  });
};

const distanceMeasurement = () => {
  if (measureflag.value == 1) {
    clearMeasurements();
  } else {
    measurement.clear();
    measurement.activeTool = view.type.toUpperCase() === "2D" ? "distance" : "direct-line";
    proxy.$refs["distanceButtonRef"].classList.add("active");
    proxy.$refs["areaButtonRef"].classList.remove("active");
    measureflag.value = 1;
  }
};
const areaMeasurement = () => {
  if (measureflag.value == 2) {
    clearMeasurements();
  } else {
    measurement.clear();
    measurement.activeTool = "area";
    proxy.$refs["distanceButtonRef"].classList.remove("active");
    proxy.$refs["areaButtonRef"].classList.add("active");
    measureflag.value = 2;
  }
};

const clearMeasurements = () => {
  measureflag.value = 0;
  proxy.$refs["distanceButtonRef"].classList.remove("active");
  proxy.$refs["areaButtonRef"].classList.remove("active");
  measurement?.clear();
};
//sublayers的id和图层树的id不匹配
const setPopupByNode = (node) => {
  for (let i = 0; i < node.layers.length; i++) {
    let subnode = node.layers[i];
    if (subnode.infos.fields) {
      // console.log(subnode.id)
      let maplayerid = subnode.id.split("-")[0];
      let mapsublayerid = subnode.id.split("-")[1];
      let maplayer = map.findLayerById(maplayerid);
      console.log("maplayer", maplayer);
      let mapsublayer = maplayer?.allSublayers.find(function (layer) {
        return layer.title == subnode.title;
      });
      console.log("mapsublayer", mapsublayer);
      let fieldInfos: { fieldName: string; label: string }[] = [];
      if (subnode.infos.fields) {
        for (let j = 0; j < subnode.infos.fields.length; j++) {
          let fieldinfo = {
            fieldName: subnode.infos.fields[j].name,
            label: subnode.infos.fields[j].alias,
          };
          fieldInfos.push(fieldinfo);
        }
      }
      if (fieldInfos.length == 0) {
        console.log("fieldInfos---", fieldInfos, maplayer);
      }
      let template = {
        title: subnode.title,
        content: [
          {
            type: "fields",
            fieldInfos: fieldInfos,
          },
        ],
        outFields: ["*"],
        returnGeometry: true,
      };
      mapsublayer.popupTemplate = template;
      mapsublayer.returnGeometry = true;
    }
    if (subnode.layers) {
      setPopupByNode(subnode);
    }
  }
};
</script>

<template>
  <div id="mapcontainer" ref="mapcontainerRef">
    <div class="menuContent" v-show="viewWidth == `calc(100% - 250px)`">
      <el-tree
        :data="allLayersTree"
        check-strictly
        style="width: 100%; height: 100%; overflow: auto; border: 1px solid #ebeef5"
        node-key="id"
        highlight-current
        :props="{
          children: 'layers',
          label: 'title',
        }"
        @check-change="changeLayers"
        show-checkbox
        ref="layerManagerTreeRef"
      />
    </div>

    <div id="view-div" ref="viewDivRef" :style="{ width: viewWidth }">
      <div id="topbar">
        <button
          class="esri-widget--button esri-interactive esri-icon-measure-line"
          ref="distanceButtonRef"
          @click="distanceMeasurement"
          title="测量两点/多点距离"
        ></button>
        <button
          class="esri-widget--button esri-interactive esri-icon-measure-area"
          ref="areaButtonRef"
          @click="areaMeasurement"
          title="测量面积"
        ></button>
        <button
          class="esri-widget--button esri-interactive esri-icon-collection"
          ref="layerButtonRef"
          @click="switchLayer"
          title="图层开关"
        ></button>
        <!-- <button class="esri-widget--button esri-interactive esri-icon-dock-right" id="swipeButton" ref="swipeButton"
                    @click="swipeAnalyze" title="卷帘分析"></button> -->
      </div>
    </div>
    <LandForm ref="landFormRef" />
  </div>
</template>
<style lang="scss" scoped>
/* 隐藏版权信息容器 */
:deep(.esri-attribution) {
  display: none !important;
  visibility: hidden;
}

/* 隐藏文字水印 */
:deep(.esri-attribution__sources) {
  display: none !important;
  visibility: hidden;
}

:deep(.esri-attribution__powered-by) {
  display: none !important;
  visibility: hidden;
}

#mapcontainer {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  margin: 0;
  // border: 0.5px solid yellow;
  box-sizing: border-box;
}

#view-div {
  position: absolute;
  top: 0;
  right: 0;
  height: 100%;
  padding: 0;
  margin: 0;
  border: 0.1px solid rgb(0 174 255);
}

.esri-widget--button.active,
.esri-widget--button.active:hover,
.esri-widget--button.active:focus {
  cursor: default;
  background-color: #999696;
}

.esri-widget--button.active path,
.esri-widget--button.active:hover path,
.esri-widget--button.active:focus path {
  fill: #e4e4e4;
}

.menuContent {
  position: absolute;
  left: 0;
  width: 250px;
  height: 100%;
  background: #fff;
}

:deep(.el-tree) {
  width: 100%;
  overflow: auto;
}

:deep(.el-tree > .el-tree-node) {
  display: inline-block;
  min-width: 100%;
}

// :deep(.el-menu--collapse) {
//     width: calc(var(--el-menu-icon-width) + var(--el-menu-base-level-padding) * 2);
// }
:deep(.el-menu--collapse) {
  position: absolute;
  left: 0;
  width: 50px;
  height: 100%;
}

:deep(.el-menu .el-icon) {
  width: 16px;
}
</style>
